package cn.com.smart.module.xman.etlMailRecv.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.com.smart.framework.aspectj.lang.annotation.Log;
import cn.com.smart.framework.aspectj.lang.enums.BusinessType;
import cn.com.smart.module.xman.etlMailRecv.domain.EtlMailRecv;
import cn.com.smart.module.xman.etlMailRecv.service.IEtlMailRecvService;
import cn.com.smart.framework.web.controller.BaseController;
import cn.com.smart.framework.web.page.TableDataInfo;
import cn.com.smart.framework.web.domain.AjaxResult;
import cn.com.smart.common.utils.MailConfig;
import cn.com.smart.common.utils.MailUtils;
import cn.com.smart.common.utils.poi.ExcelUtil;

/**
 * 接收邮件信息操作处理
 * 
 * @author xman
 * @date 2019-06-18
 */
@Controller
@RequestMapping("/xman/etlMailRecv")
public class EtlMailRecvController extends BaseController
{
	@Value("${smart.profile}")
    private String filePath;
	
	@Value("${mail.imap.host}")
	private String host;
	
	@Value("${mail.imap.protocol}")
	private String protocol;
	
	@Value("${mail.imap.port}")
	private int port;
	
	@Value("${mail.from}")
	private String userName;
	
	@Value("${mail.password}")
	private String password;
	
    private String prefix = "xman/etlMailRecv";
	
	@Autowired
	private IEtlMailRecvService etlMailRecvService;
	
	@RequiresPermissions("xman:etlMailRecv:view")
	@GetMapping()
	public String etlMailRecv()
	{
	    return prefix + "/etlMailRecv";
	}
	
	@RequiresPermissions("xman:etlMailRecv:list")
	@PostMapping("/list")
	@ResponseBody
	public AjaxResult list(Integer page, Integer size)
	{
		if(page == null) {
			page = 0;
		}
		if(size == null) {
			size = 10;
		}
		MailConfig config = new MailConfig();
		config.setServerHost(host);
		config.setProtocol(protocol);
		config.setPort(port);
		config.setUserName(userName);
		config.setPassword(password);
		config.setImap(true);
		config.setFilePath(filePath + "download/");
		//清除一天前的文件
		File dlPath = new File(config.getFilePath());
		if(dlPath.exists()) {
			long clear = System.currentTimeMillis() - 24 * 60 * 60 * 1000;
			for(File f : dlPath.listFiles()) {
				if(f.lastModified() < clear) {
					f.delete();
				}
			}
		}
	    try {
	    	List<JSONObject> data = MailUtils.recvEmail(page, size, config);
	    	data.forEach(m -> {
	    		Set<String> type = new HashSet<String>();
				Iterator<Object> it = m.getJSONArray("content").iterator();
				while(it.hasNext()) {
					JSONObject json = (JSONObject) it.next();
					type.add(json.getString("contentType").toLowerCase().split(";", -1)[0]);
				}
				if(type.contains("text/plain") && type.contains("text/html")) {
					it = m.getJSONArray("content").iterator();
					while(it.hasNext()) {
						JSONObject json = (JSONObject) it.next();
						if(json.getString("contentType").toLowerCase().startsWith("text/plain;")) {
							it.remove();
						}
					}
				}
	    	});
			return AjaxResult.success(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return AjaxResult.error("查询失败");
	}
	
	/**
	 * 查询接收邮件列表
	 */
	@PostMapping("/list2")
	@ResponseBody
	public TableDataInfo list(EtlMailRecv etlMailRecv)
	{
		startPage();
        List<EtlMailRecv> list = etlMailRecvService.selectList(etlMailRecv);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出接收邮件列表
	 */
	@RequiresPermissions("xman:etlMailRecv:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(EtlMailRecv etlMailRecv)
    {
    	List<EtlMailRecv> list = etlMailRecvService.selectList(etlMailRecv);
        ExcelUtil<EtlMailRecv> util = new ExcelUtil<EtlMailRecv>(EtlMailRecv.class);
        return util.exportExcel(list, "etlMailRecv");
    }
	
	/**
	 * 新增接收邮件
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存接收邮件
	 */
	@RequiresPermissions("xman:etlMailRecv:add")
	@Log(title = "接收邮件", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(EtlMailRecv etlMailRecv)
	{		
		return toAjax(etlMailRecvService.insert(etlMailRecv));
	}

	/**
	 * 修改接收邮件
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap)
	{
		EtlMailRecv etlMailRecv = etlMailRecvService.selectById(id);
		mmap.put("etlMailRecv", etlMailRecv);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存接收邮件
	 */
	@RequiresPermissions("xman:etlMailRecv:edit")
	@Log(title = "接收邮件", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(EtlMailRecv etlMailRecv)
	{		
		return toAjax(etlMailRecvService.updateById(etlMailRecv));
	}
	
	/**
	 * 删除接收邮件
	 */
	@RequiresPermissions("xman:etlMailRecv:remove")
	@Log(title = "接收邮件", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(etlMailRecvService.deleteBatchIds(ids));
	}
	
	@GetMapping("/fileDownload")
	@ResponseBody
    public AjaxResult fileDownload(String fileName, String originalName, HttpServletResponse response) {
		if(StringUtils.isNotEmpty(fileName)) {
			File file = new File(filePath + "download/" + fileName);
			if(file.exists()) {
				BufferedInputStream bis = null;
				final int MAX_SIZE = 4096;
				int len;
				byte[] buffer = new byte[MAX_SIZE]; 
				try {
	    			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isEmpty(originalName)?fileName:originalName, "UTF-8"));
	    			response.addHeader("Content-Length","" + file.length());
	    			bis = new BufferedInputStream(new FileInputStream(file));
	    			OutputStream os = response.getOutputStream();
	    			while((len = bis.read(buffer, 0, MAX_SIZE)) != -1) {
	    				os.write(buffer, 0, len);
	    			}
	    			os.flush();
	    			os.close();
	    			return AjaxResult.success("下载成功");
		    	} catch(Exception e) {
		    		e.printStackTrace();
		    	} finally {
		    		if(bis != null) {
		    			try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
		    		}
		    	}
			} else {
    			AjaxResult.error("文件不存在");
    		}
		}
        return AjaxResult.error("下载失败");
    }
	
}
